package com.yunbao.main.activity;

import android.Manifest;
;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants;
import com.yunbao.common.activity.AbsActivity;

import com.yunbao.common.adapter.ViewPagerAdapter;
import com.yunbao.common.bean.ConfigBean;
import com.yunbao.common.business.acmannger.ActivityMannger;
import com.yunbao.common.custom.TabButtonGroup;
import com.yunbao.common.http.CommonHttpConsts;
import com.yunbao.common.http.CommonHttpUtil;
import com.yunbao.common.interfaces.CommonCallback;
import com.yunbao.common.utils.DialogUitl;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.LocationUtil;
import com.yunbao.common.utils.ProcessResultUtil;
import com.yunbao.common.utils.RouteUtil;
import com.yunbao.common.utils.SpUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.VersionUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.common.views.AbsMainViewHolder;
import com.yunbao.im.event.ImUnReadCountEvent;
import com.yunbao.im.utils.ImMessageUtil;
import com.yunbao.main.R;
import com.yunbao.main.bean.commit.DressingCommitBean;
import com.yunbao.main.event.OpenDrawEvent;
import com.yunbao.main.http.MainHttpConsts;
import com.yunbao.main.http.MainHttpUtil;
import com.yunbao.main.views.MainHomeViewHolder;
import com.yunbao.main.views.MainMeViewHolder2;
import com.yunbao.main.views.MainMessageViewHolder;
import com.yunbao.main.views.SelectConditionViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-05-28
// +———————————————————————————————————
@Route(path = RouteUtil.PATH_MAIN)
public class MainActivity extends AbsActivity {
    private static final String TAG = "MainActivity";
    private static final int PAGE_COUNT = 3;
    private TabButtonGroup mTabButtonGroup;
    private ViewPager mViewPager;
    private TextView mRedPoint;
    private List<FrameLayout> mViewList;
    private MainHomeViewHolder mHomeViewHolder;

    private MainMessageViewHolder mMessageViewHolder;
    private MainMeViewHolder2 mMeViewHolder;
    private AbsMainViewHolder[] mViewHolders;
    private ProcessResultUtil mProcessResultUtil;
    private boolean mFristLoad;
    private long mLastClickBackTime;//上次点击back键的时间
    private ViewGroup mDrawlayoutContainer;

    private SelectConditionViewHolder selectConditionViewHolder;
    private DrawerLayout mDrawerLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void main() {
        ActivityMannger.getInstance().setBaseActivity(this);
        SpUtil.getInstance().setBooleanValue(Constants.FIRST_LOGIN, false);
        mTabButtonGroup = findViewById(R.id.tab_group);
        mDrawlayoutContainer = findViewById(R.id.drawlayout_container);
        mDrawerLayout = findViewById(R.id.drawlayout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        mViewPager = findViewById(R.id.viewPager);
        if (PAGE_COUNT > 1) {
            mViewPager.setOffscreenPageLimit(PAGE_COUNT - 1);
        }
        mViewList = new ArrayList<>();
        for (int i = 0; i < PAGE_COUNT; i++) {
            FrameLayout frameLayout = new FrameLayout(mContext);
            frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mViewList.add(frameLayout);
        }
        mViewPager.setAdapter(new ViewPagerAdapter(mViewList));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                loadPageData(position, true);
                if (mViewHolders != null) {
                    for (int i = 0, length = mViewHolders.length; i < length; i++) {
                        AbsMainViewHolder vh = mViewHolders[i];
                        if (vh != null) {
                            vh.setShowed(position == i);
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mTabButtonGroup.setViewPager(mViewPager);
        mViewHolders = new AbsMainViewHolder[PAGE_COUNT];
        mRedPoint = findViewById(R.id.red_point);
        mProcessResultUtil = new ProcessResultUtil(this);
        EventBus.getDefault().register(this);
        CommonAppConfig.getInstance().setLaunched(true);
        CommonAppConfig.getInstance().setLaunchTime(System.currentTimeMillis() / 1000);
        mFristLoad = true;
        openSelectSelectConditionViewHolder();
    }

    public void openSelectSelectConditionViewHolder() {
        if (selectConditionViewHolder == null) {
            selectConditionViewHolder = new SelectConditionViewHolder(this, mDrawlayoutContainer, mDrawerLayout);
            selectConditionViewHolder.addToParent();
            selectConditionViewHolder.subscribeActivityLifeCycle();
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        L.e("onNewIntent==");
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 检查版本更新
     */
    private void checkVersion() {
        CommonAppConfig.getInstance().getConfig(new CommonCallback<ConfigBean>() {
            @Override
            public void callback(ConfigBean configBean) {
                if (configBean != null) {
                    if (configBean.getMaintainSwitch() == 1) {//开启维护
                        DialogUitl.showSimpleTipDialog(mContext, WordUtil.getString(R.string.main_maintain_notice), configBean.getMaintainTips());
                    }
                    if (!VersionUtil.isLatest(configBean.getVersion())) {
                        VersionUtil.showDialog(mContext, configBean.getUpdateDes(), configBean.getDownloadApkUrl());
                    }
                }
            }
        });
    }




    @Override
    protected void onResume() {
        super.onResume();
        L.e(TAG, "----onResume----");
        if (mFristLoad) {
            mFristLoad = false;
            checkPermissions();
            loginIM();
            loadPageData(0, true);
            if (mHomeViewHolder != null) {
                mHomeViewHolder.setShowed(true);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        L.e(TAG, "----onPause----");
    }

    /**
     * 检查权限
     */

    private void checkPermissions() {
        mProcessResultUtil.requestPermissions(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_COARSE_LOCATION,
        }, new CommonCallback<Boolean>() {
            @Override
            public void callback(Boolean result) {
                if (result) {
                    getLocation();
                }
            }
        });
    }

    /**
     * 获取所在位置, 启动定位
     */
    private void getLocation() {
        LocationUtil.getInstance().startLocation();
    }

    /**
     * 登录IM
     */

    private void loginIM() {
        String uid = CommonAppConfig.getInstance().getUid();
        ImMessageUtil.getInstance().loginImClient(uid);
    }

    @Override
    protected void onDestroy() {
        L.e(TAG, "----onDestroy----");
        ActivityMannger.getInstance().releaseBaseActivity(this);
        if (mTabButtonGroup != null) {
            mTabButtonGroup.cancelAnim();
        }
        EventBus.getDefault().unregister(this);
        MainHttpUtil.cancel(CommonHttpConsts.GET_CONFIG);
        MainHttpUtil.cancel(MainHttpConsts.CHECK_AGENT);
        CommonHttpUtil.cancel(CommonHttpConsts.SET_LOCAITON);
        LocationUtil.getInstance().stopLocation();
        if (mProcessResultUtil != null) {
            mProcessResultUtil.release();
        }

        CommonAppConfig.getInstance().setLaunched(false);
        super.onDestroy();
    }

    public static void forward(Context context) {
        forward(context, false);
    }

    public static void forward(Context context, boolean firstLogin) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(Constants.FIRST_LOGIN, firstLogin);
        context.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImUnReadCountEvent(ImUnReadCountEvent e) {
        L.e(TAG, "onImUnReadCountEvent未读消息总数--->" + e.getUnReadCount());
        String unReadCount = e.getUnReadCount();
        if (!TextUtils.isEmpty(unReadCount)) {
            setUnReadCount(unReadCount);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOpenDrawLayout(OpenDrawEvent drawEvent) {
        DressingCommitBean dressingCommitBean = drawEvent.getDressingCommitBean();
        selectConditionViewHolder.setCondition(dressingCommitBean);
        mDrawerLayout.openDrawer(Gravity.RIGHT);
    }

    /**
     * 显示未读消息
     */
    private void setUnReadCount(String unReadCount) {
        if (mRedPoint != null) {
            if ("0".equals(unReadCount)) {
                if (mRedPoint.getVisibility() == View.VISIBLE) {
                    mRedPoint.setVisibility(View.INVISIBLE);
                }
            } else {
                if (mRedPoint.getVisibility() != View.VISIBLE) {
                    mRedPoint.setVisibility(View.VISIBLE);
                }
            }
            mRedPoint.setText(unReadCount);
        }
    }

    @Override
    public void onBackPressed() {
        long curTime = System.currentTimeMillis();
        if (curTime - mLastClickBackTime > 2000) {
            mLastClickBackTime = curTime;
            ToastUtil.show(R.string.main_click_next_exit);
            return;
        }
        super.onBackPressed();
    }

    private void loadPageData(int position, boolean needlLoadData) {
        if (mViewHolders == null) {
            return;
        }

        AbsMainViewHolder vh = mViewHolders[position];
        if (vh == null) {
            if (mViewList != null && position < mViewList.size()) {
                FrameLayout parent = mViewList.get(position);
                if (parent == null) {
                    return;
                }
                if (position == 0) {
                    mHomeViewHolder = new MainHomeViewHolder(mContext, parent);
                    vh = mHomeViewHolder;
                } else if (position == 1) {
                    mMessageViewHolder = new MainMessageViewHolder(mContext, parent);
                    vh = mMessageViewHolder;
                } else if (position == 2) {
                    mMeViewHolder = new MainMeViewHolder2(mContext, parent);
                    vh = mMeViewHolder;
                }
                if (vh == null) {
                    return;
                }
                mViewHolders[position] = vh;
                vh.addToParent();
                vh.subscribeActivityLifeCycle();
            }
        }
        if (needlLoadData && vh != null) {
            vh.loadData();
        }
    }



}
